var app = getApp();
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function extend() {
	var o={};
	var i =0,len=arguments.length;
	for(;i<len;i++){
		var source = arguments[i];
		for(var prop in source){
			o[prop] = source[prop];
		}
	}
	return o;
}
function getExtConfig(callBack){
  wx.getExtConfig({
    success: function (res) {
      if(typeof callBack == 'function'){
        callBack(res.extConfig);
      }
    }
  });
}
function request(obj,timeout = 3600,cacheKey="",delKey=[]){
  let key = cacheKey != "" ? cacheKey : obj.url;
  let url = 'https://shop.bidcms.com/app.php?r=' + obj.url;
  if (obj.url.substr(0,4) == 'http'){
    url = obj.url;
  }
  if (delKey.length>0){
    for(var i in delKey){
      wx.removeStorageSync(delKey[i]);
    }
    
  }
  var res = key!=''?wx.getStorageSync(key):null;
  if (res != null && res.data && timeout>0) {
    if(new Date().getTime() - res.ctime >= timeout*1000){
      wx.removeStorageSync(key);
    }
    obj.success(res);
  } else {
    wrequest(url, obj.data).then((res) => {
      if (timeout >= 0 && key != "" && res.data && res.data.data && Object.keys(res.data.data).length > 0 && res.data.code == 0) {
        wx.setStorageSync(key, { "data": res.data, "ctime": new Date().getTime()});
      }
      obj.success(res);
    })
  }
  
}
/**
 * 微信的的request
 */
function wrequest(url, data = {}, method = "POST") {
  return new Promise(function (resolve, reject) {
    getExtConfig(function(extConfig){
      let datas = {}
      datas.pid = extConfig.pid;
      datas.appid = extConfig.appid;
	    datas.version = extConfig.version;
      let token = wx.getStorageSync('token');
      if (token && !data.token){
        datas.token = token;
      }
	  datas = extend(datas,data);
      wx.request({
        url: url,
        data: datas,
        method: method,
        header: {
          'Content-Type': 'application/json',
          'X-Nideshop-Token': wx.getStorageSync('token')
        },
        success: function (res) {
          if (res.statusCode == 200) {
            resolve(res);
          } else {
            reject(res.statusCode);
          }

        },
        fail: function (err) {
          reject(err)
          console.log("failed")
        }
      })
    });
    
  });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}

function storage(key,data){
   if(wx.getStorageSync(key)){
     return wx.getStorageSync(key);
   }
   wx.setStorageSync(key, data);
   return data;
}
module.exports = {
  formatTime: formatTime,
  request,
  redirect,
  showErrorToast,
  checkSession,
  login,
  getUserInfo
}

